#数据准备
import pandas as pd
from sklearn.model_selection import train_test_split

data_file = r"D:\git code\xiangmu\boke\2025.10.9\03\logi-y.txt"
raw_data = pd.read_csv(data_file, delimiter=",", encoding="utf-8")
x = raw_data.iloc[:, 0:2].values             # 特征：科目1成绩、科目2成绩
y = raw_data.iloc[:, 2].values               # 标签：是否录取
x_train, x_test, y_train, y_test = train_test_split( x, y,test_size=0.3,  random_state=42  )


# 查看数据基本信息
print(f"总样本数：{x.shape[0]}，训练集样本数：{x_train.shape[0]}，测试集样本数：{x_test.shape[0]}")
print(f"科目1成绩范围：{x[:, 0].min():.1f}~{x[:, 0].max():.1f}，均值：{x[:, 0].mean():.1f}")
print(f"科目2成绩范围：{x[:, 1].min():.1f}~{x[:, 1].max():.1f}，均值：{x[:, 1].mean():.1f}")
print(f"录取样本数：{y[y==1].shape[0]}，未录取样本数：{y[y==0].shape[0]}")
print(f"训练集形状：{x_train.shape}，测试集形状：{x_test.shape}")




from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
# 训练与评估逻辑回归模型
model = LogisticRegression(solver="liblinear",random_state=42)
model.fit(x_train, y_train)
mc = model.score(x_test, y_test)
y_test_pred = model.predict(x_test)
ac = accuracy_score(y_test, y_test_pred)

print(f"训练集准确率：{model.score(x_train, y_train):.4f}")
print(f"测试集准确率（model.score）：{mc:.4f}")
print(f"测试集准确率（accuracy_score）：{ac:.4f}")




import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np

# 绘制分类可视化图形
N, M = 500, 500  
# 按数据实际范围设置坐标轴
t1 = np.linspace(x[:, 0].min()-2, x[:, 0].max()+2, N)  # 横轴：科目1成绩（扩展2个单位避免样本溢出）
t2 = np.linspace(x[:, 1].min()-2, x[:, 1].max()+2, M)  # 纵轴：科目2成绩

# 生成网格矩阵
x1, x2 = np.meshgrid(t1, t2)
x_new = np.stack((x1.flat, x2.flat), axis=1)
y_predict = model.predict(x_new)  # 预测所有网格点的类别
y_hat = y_predict.reshape(x1.shape)  # 重塑为网格形状（匹配x1的维度，便于绘图）
logi_cmap = ListedColormap(["#ACF080", "#A0A0FF"]) 

plt.pcolormesh(x1, x2, y_hat, cmap=logi_cmap, alpha=0.5)
plt.scatter(x[y==0, 0], x[y==0, 1], s=50,   c="blue",  marker="o",  label="未录取")
plt.scatter(x[y==1, 0], x[y==1, 1],s=50,c="red",marker="^",label="已录取")

plt.rcParams["font.sans-serif"] = ["SimHei"]  
plt.xlabel("科目1成绩", fontsize=12) 
plt.ylabel("科目2成绩", fontsize=12)  
plt.title("招聘考试成绩逻辑回归分类结果", fontsize=14) 
plt.legend(fontsize=10)  
plt.show()